﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using Bridge.Base.Constructs;
using Bridge.Base.Converter;
using Bridge.Base.Utilities;
using Bridge.Objects;
using System.Threading;

namespace Bridge.UI
{
    /// <summary>
    /// Interaction logic for ImportStatblock.xaml
    /// </summary>
    public partial class ImportStatblock : UserControl
    {
        public static readonly RoutedEvent CharacterParsedEvent = EventManager.RegisterRoutedEvent(
            "CharacterParsed",
            RoutingStrategy.Bubble,
            typeof(RoutedEventHandler),
            typeof(ImportStatblock));

        public ImportStatblock()
        {
            InitializeComponent();

            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }
            mAssembliesReloadedEventHandler = new EventHandler(Main_AssembliesReloaded);
            Main.AssembliesReloaded += mAssembliesReloadedEventHandler;
        }

        ~ImportStatblock()
        {
            Main.AssembliesReloaded -= mAssembliesReloadedEventHandler;
        }

        public event RoutedEventHandler CharacterParsed
        {
            add { AddHandler(CharacterParsedEvent, value); }
            remove { RemoveHandler(CharacterParsedEvent, value); }
        }

        private EventHandler mAssembliesReloadedEventHandler;

        private void RaiseCharacterParsedEvent(Character character)
        {
            RaiseEvent(new RoutedEventArgs(CharacterParsedEvent, character));
        }

        private void LoadStatblockImporters()
        {
            try
            {
                List<Type> statblockImporters = new List<Type>(typeof(StatblockConverter).GetCompatibleTypes());
                List<StatblockConverter> converters = new List<StatblockConverter>();

                foreach (Type type in statblockImporters)
                {
                    converters.Add((StatblockConverter)type.GetConstructor(Type.EmptyTypes).Invoke(null));
                }

                comboBoxImporter.ItemsSource = converters;
            }
            catch (Exception ex)
            {
                Log.NormalLog.Warn("Could not load statblock importers.", ex);
                WarningWindow.ShowDialog(WarningWindow.WarningType.OK, "Could not load statblock importers.", ex.ToString(), "Statblock importer load failure.");
            }
        }

        private void comboBoxImporter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                textBoxText.IsEnabled = true;
            }
            else
            {
                textBoxText.IsEnabled = false;
                buttonCreate.IsEnabled = false;
            }
        }

        private void buttonCreate_Click(object sender, RoutedEventArgs e)
        {
            DateTime startTime = DateTime.Now;
            buttonCreate.Tag = "Processing";
            StatblockConverter converter = (StatblockConverter)comboBoxImporter.SelectedItem;
            try
            {
                Character character = converter.ConvertStatblock(textBoxText.Text);
                RaiseCharacterParsedEvent(character);
                textBoxText.Text = string.Empty;
                TimeSpan timeSpan = DateTime.Now.Subtract(startTime);
                WarningWindow.ShowDialog(WarningWindow.WarningType.OK, string.Format("Character {0} parsed successfully.", character.Name), null, "Character Parsed");
                Log.MetricsLog.InfoFormat("Parsed {0} successfully using {1}, Time Taken: {2}", character.Name, converter.Name, timeSpan);
            }
            catch (Exception ex)
            {
                Log.NormalLog.Warn(string.Format("Attempting to parse statblock using {0} failed. First 50 characters: {1}", converter.Name, textBoxText.Text.Length > 50 ? textBoxText.Text.Remove(50) : textBoxText.Text), ex);
                WarningWindow.ShowWarning(WarningWindow.WarningType.OK, string.Format("Parse attempt failed! This is a package error. Notify the package creator of this issue.\nError Time: {0}", DateTime.Now), ex.ToString(), "Parse Exception");
            }
            buttonCreate.Tag = "Stopped";
        }

        private void Main_AssembliesReloaded(object sender, EventArgs e)
        {
            LoadStatblockImporters();
        }



        private void textBoxText_TextChanged(object sender, TextChangedEventArgs e)
        {
            buttonCreate.IsEnabled = !string.IsNullOrEmpty(textBoxText.Text);
        }
    }
}
